import Flutter
import UIKit
import UserNotifications
import ThingSmartBaseKit
import ThingModuleManager
import ThingSmartLogger
import flutter_secure_storage
import tuya_home_sdk_flutter

@main
@objc class AppDelegate: FlutterAppDelegate {
    let flutterEngine = FlutterEngine(name: "casdon_flutter_engine")
    private var toolChannel: FlutterMethodChannel?
   
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {

        // Push notification setup
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.delegate = self
            center.requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
                if let error = error {
                    print("Push authorization error: \(error)")
                } else {
                    print("Push authorization granted: \(granted)")
                }
            }
        } else {
            let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
            application.registerUserNotificationSettings(settings)
        }
        application.registerForRemoteNotifications()

        flutterEngine.run()

        // 2. 注册插件到该引擎
        GeneratedPluginRegistrant.register(with: flutterEngine)
        // 单引擎多VC：统一使用flutterEngine，保证Provider共享
        TuyaHomeSdkFlutterPlugin.set(engine: flutterEngine)


        // 3. 配置导航控制器
        // 如果 engine 已经附着过其他 FlutterViewController，先解绑
        flutterEngine.viewController = nil
        let controller = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
        controller.edgesForExtendedLayout = [.top]
      

        let navController = UINavigationController(rootViewController: controller)
        navController.setNavigationBarHidden(true, animated: false)
        navController.delegate = self
        window?.rootViewController = navController
        window.makeKeyAndVisible()
        
        /// 调试 RN
        // 方法通道，供 Flutter 调用原生能力
        toolChannel = FlutterMethodChannel(
            name: "native_tool",
            binaryMessenger: controller.binaryMessenger
        )
        toolChannel?.setMethodCallHandler { [weak self] call, result in
            switch call.method {
            case "openRnTool":
                self?.openRnTool()
                result(nil)
            default:
                result(FlutterMethodNotImplemented)
            }
        }
        //////////////////////////////////////////
        

        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }

    
    
    
    // MARK: - APNs callbacks

    override func application(
        _ application: UIApplication,
        didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
    ) {
        super.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
        let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
        print("APNs device token: \(token)")


        ThingSmartSDK.sharedInstance().deviceToken = deviceToken
    }

    override func application(
        _ application: UIApplication,
        didFailToRegisterForRemoteNotificationsWithError error: Error
    ) {
        super.application(application, didFailToRegisterForRemoteNotificationsWithError: error)
        print("Failed to register for remote notifications: \(error)")
    }

    @available(iOS 10.0, *)
    override  func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
    ) {
        // 前台展示通知
        completionHandler([.alert, .badge, .sound])
    }

    @available(iOS 10.0, *)
    override  func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        didReceive response: UNNotificationResponse,
        withCompletionHandler completionHandler: @escaping () -> Void
    ) {
        // 点击通知的处理，如果需要可以通过 MethodChannel 传给 Flutter
        print("User tapped notification: \(response.notification.request.identifier)")
        completionHandler()
    }

    // Flutter 调用的原生方法
    private func openRnTool() {
        print("openRnTool called from Flutter")
        // 在这里填入实际的 RN 调试/工具逻辑
        let debugConfig = "openRNDebugConfig"
        if let service = ThingModule.routeService() {
            service.openRoute(debugConfig, withParams: nil)
        }
        
    }
}


// 解决从涂鸦面板设置返回到首页时，显示异常的问题
extension AppDelegate: UINavigationControllerDelegate {
    func navigationController(
        _ navigationController: UINavigationController,
        willShow viewController: UIViewController,
        animated: Bool
    ) {
        let controllers = navigationController.viewControllers
        let description = controllers
            .map { vc in
                let address = Unmanaged.passUnretained(vc).toOpaque()
                return "\(type(of: vc)) @ \(address)"
            }
            .joined(separator: " | ")
        print("119615 \n--------");
        print("119615 Nav willShow -> target: \(type(of: viewController)) @ \(Unmanaged.passUnretained(viewController).toOpaque()); stack: [\(description)]")
        
        if let flutterVC = viewController as? FlutterViewController {
            // 单引擎多VC：确保即将显示的FlutterViewController被attach到engine
            let engine = flutterVC.engine
            if engine.viewController != flutterVC {
                engine.viewController = flutterVC
            }
            
            navigationController.navigationBar.isHidden = true;
            
            // 2. 重置 FlutterViewController 的 frame
            viewController.view.frame = UIScreen.main.bounds
        
            // 3. 强制布局更新
            DispatchQueue.main.async {
                navigationController.setNavigationBarHidden(true, animated: false)
                viewController.view.setNeedsLayout()
                viewController.view.layoutIfNeeded()
            }
        }
        
    }
}
